"use client"

import { useState, useEffect, useRef } from 'react'
import { textStyles } from '../lib/fontConfig'

interface StrokeAnimationSVGProps {
  character: string
  svgPath?: string
  strokeOrder: string[]
  isAnimating: boolean
  currentStroke: number
  onStrokeComplete: (strokeIndex: number) => void
  onAnimationComplete: () => void
}

export function StrokeAnimationSVG({
  character,
  svgPath,
  strokeOrder,
  isAnimating,
  currentStroke,
  onStrokeComplete,
  onAnimationComplete
}: StrokeAnimationSVGProps) {
  const svgRef = useRef<SVGSVGElement>(null)
  const [animationProgress, setAnimationProgress] = useState(0)

  // 临时的简化SVG路径数据（等待开源社区数据替换）
  const getTemporaryStrokePaths = (char: string) => {
    const strokePaths: { [key: string]: string[] } = {
      '木': [
        'M50,80 L150,80',           // 横
        'M100,60 L100,140',        // 竖
        'M80,100 L60,130',         // 撇
        'M120,100 L160,130'        // 捺
      ],
      '水': [
        'M100,60 L100,120 Q105,125 110,120',  // 竖钩
        'M80,90 Q90,85 100,90',               // 横撇
        'M70,110 L50,140',                    // 撇
        'M130,110 L170,140'                   // 捺
      ]
    }
    return strokePaths[char] || strokePaths['木']
  }

  const strokePaths = getTemporaryStrokePaths(character)

  useEffect(() => {
    if (!isAnimating) {
      setAnimationProgress(0)
      return
    }

    if (currentStroke >= strokePaths.length) {
      onAnimationComplete()
      return
    }

    // 模拟笔画动画进度
    const animationDuration = 2000 // 2秒完成一个笔画
    const startTime = Date.now()

    const animate = () => {
      const elapsed = Date.now() - startTime
      const progress = Math.min(elapsed / animationDuration, 1)
      
      setAnimationProgress(progress)

      if (progress < 1) {
        requestAnimationFrame(animate)
      } else {
        // 当前笔画完成
        setTimeout(() => {
          onStrokeComplete(currentStroke)
        }, 500) // 停顿0.5秒再开始下一笔画
      }
    }

    requestAnimationFrame(animate)
  }, [isAnimating, currentStroke, strokePaths.length, onStrokeComplete, onAnimationComplete])

  return (
    <div className="w-full h-64 flex flex-col items-center">
      {/* SVG动画区域 */}
      <div className="relative w-full h-48 bg-white rounded-lg border-2 border-gray-200 overflow-hidden">
        <svg
          ref={svgRef}
          viewBox="0 0 200 200"
          className="w-full h-full"
          style={{ background: 'linear-gradient(45deg, #f8f9fa 25%, transparent 25%), linear-gradient(-45deg, #f8f9fa 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #f8f9fa 75%), linear-gradient(-45deg, transparent 75%, #f8f9fa 75%)', backgroundSize: '20px 20px', backgroundPosition: '0 0, 0 10px, 10px -10px, -10px 0px' }}
        >
          {/* 田字格辅助线 */}
          <defs>
            <pattern id="grid" width="100" height="100" patternUnits="userSpaceOnUse">
              <path d="M 100 0 L 0 0 0 100" fill="none" stroke="#e0e0e0" strokeWidth="1" strokeDasharray="2,2"/>
              <path d="M 50 0 L 50 100 M 0 50 L 100 50" fill="none" stroke="#f0f0f0" strokeWidth="1" strokeDasharray="1,1"/>
            </pattern>
          </defs>
          <rect width="200" height="200" fill="url(#grid)" opacity="0.3"/>
          
          {/* 中心十字线 */}
          <line x1="100" y1="0" x2="100" y2="200" stroke="#e0e0e0" strokeWidth="1" strokeDasharray="3,3" opacity="0.5"/>
          <line x1="0" y1="100" x2="200" y2="100" stroke="#e0e0e0" strokeWidth="1" strokeDasharray="3,3" opacity="0.5"/>

          {/* 已完成的笔画 */}
          {strokePaths.slice(0, currentStroke).map((path, index) => (
            <path
              key={`completed-${index}`}
              d={path}
              fill="none"
              stroke="#2563eb"
              strokeWidth="4"
              strokeLinecap="round"
              strokeLinejoin="round"
              opacity="0.7"
            />
          ))}

          {/* 当前正在绘制的笔画 */}
          {isAnimating && currentStroke < strokePaths.length && (
            <path
              d={strokePaths[currentStroke]}
              fill="none"
              stroke="#dc2626"
              strokeWidth="5"
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeDasharray="1000"
              strokeDashoffset={1000 * (1 - animationProgress)}
              style={{
                transition: 'none',
                filter: 'drop-shadow(0 0 3px rgba(220, 38, 38, 0.5))'
              }}
            />
          )}

          {/* 起笔点指示器 */}
          {isAnimating && currentStroke < strokePaths.length && (
            <circle
              cx={strokePaths[currentStroke].match(/M(\d+)/)?.[1] || '100'}
              cy={strokePaths[currentStroke].match(/M\d+,(\d+)/)?.[1] || '100'}
              r="3"
              fill="#dc2626"
              className="animate-pulse"
            />
          )}
        </svg>

        {/* 动画状态指示器 */}
        {isAnimating && (
          <div className="absolute top-2 right-2 bg-red-500 text-white px-2 py-1 rounded-full text-xs animate-pulse">
            第 {currentStroke + 1} 画
          </div>
        )}
      </div>

      {/* 字符显示和进度 */}
      <div className="mt-3 text-center">
        <div className={`${textStyles.primaryCharacter} text-gray-800 mb-2`}>
          {character}
        </div>
        
        {isAnimating && (
          <div className="w-32 bg-gray-200 rounded-full h-2">
            <div 
              className="bg-blue-500 h-2 rounded-full transition-all duration-300"
              style={{ width: `${(currentStroke / strokePaths.length) * 100}%` }}
            />
          </div>
        )}
        
        <div className={`${textStyles.caption} text-gray-600 mt-1`}>
          {isAnimating 
            ? `正在绘制：${strokeOrder[currentStroke] || '完成'}`
            : '点击播放按钮开始动画'
          }
        </div>
      </div>

      {/* 开源数据集成提示 */}
      <div className="mt-2 text-center">
        <div className={`${textStyles.caption} text-blue-600 bg-blue-50 px-3 py-1 rounded-full`}>
          💡 等待集成开源社区SVG数据
        </div>
      </div>
    </div>
  )
} 